<?php
declare (strict_types = 1);
namespace app\admin\controller;

use think\facade\Session;
use think\Request;
use think\facade\View;
use think\exception\ValidateException;

use app\admin\validate\CateValidate;

use app\admin\model\Cate;

class CateController extends BaseController
{
    // 渲染分类列表页面
    public function cate_list()
    {   
        return view();
    }

    // 渲染分类添加页面
    public function cate_add()
    {   
        return view();
    }

    // 获取分类列表
    public function cate_data()
    {   
        $cateModel = new Cate();
        $data = input('get.');

        // 验证数据
        try{
            validate(CateValidate::class)->scene('list')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $where = [];

        // 搜索条件
        if($data && isset($data['key'])){
            if(!empty($data['key']['name'])){
                $where[] = ['name', 'like', '%' . $data['key']['name'] . '%'];
            }
        }

        $count = $cateModel->getNum($where)['data'];

        $field = 'id, name, type';
        $list = $cateModel->getList($where, 1, $data['page'], $data['limit'], $field);

        if($list['code'] != 'ok'){
            $this->error_back('暂无数据~');
        }

        $this->success_back('ok', $list['data'], $count);
    }

    // 分类添加
    public function cateAdd()
    {   
        $cateModel = new Cate();
        $data = input('post.');

        // 验证数据
        try{
            validate(CateValidate::class)->scene('add')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }
        
        $flag = $cateModel->add($data);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('添加成功');
    }

    // 分类信息修改(单元格修改)
    public function setCateOnlyEdit()
    {   
        $cateModel = new Cate();
        $data = input('post.');
        $editArr = ['id' => $data['id'], $data['field'] => $data['value']];

        // 验证数据
        try{
            validate(CateValidate::class)->scene('edit')->check($editArr);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }
        
        $flag = $cateModel->edit($editArr);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('修改成功');
    }

    // 删除分类
    public function cate_del()
    {
        $cateModel = new Cate();
        $data = input('post.');

        // 验证数据
        try{
            validate(CateValidate::class)->scene('show')->check($data);
        }catch(ValidateException $e){
            $this->error_back($e->getError());
        }

        $flag = $cateModel->del(['id' => $data['id']]);

        if($flag['code'] != 'ok'){
            $this->error_back($flag['msg']);
        }

        $this->success_back('删除成功');
    }
}
